package com.cxy.controller.admin;

import com.cxy.dto.UserLoginDTO;
import com.cxy.entity.User;
import com.cxy.result.Result;
import com.cxy.service.UserService;
import com.cxy.utils.JwtUtils;
import com.cxy.vo.AdminLoginVO;
import com.cxy.vo.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@Api(tags = "管理端登录")
@RestController
@RequestMapping("/admin/login")
@Slf4j
public class LoginController {
    @Autowired
    private UserService userService;
    /**
     * 用户登录
     */
    @ApiOperation("管理端登录")
    @PostMapping
    public Result<AdminLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        //通过密码和账号查看用户是否存在
        User user = userService.login(userLoginDTO);
        //登录成功下发jwt令牌
        if (user!=null){
           Map<String,Object> map =new HashMap<>();
           map.put("id",user.getId());
           String jwt = JwtUtils.generateJwt(map);
           AdminLoginVO adminLoginVO =new AdminLoginVO();
           adminLoginVO.setId(user.getId());
           adminLoginVO.setName(user.getName());
           adminLoginVO.setUserName(user.getUsername());
           adminLoginVO.setToken(jwt);
           return Result.success(adminLoginVO);
        }
        return Result.error("密码或者用户名错误");
    }
}
